//
//  LoginViewController.m
//  NiuBanJin
//
//  Created by Billy on 15/9/24.
//  Copyright (c) 2015年 zzjr. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "User.h"
#import "CustomTabBarViewController.h"
#import "RegisterViewController.h"

@interface LoginViewController () 

@property (nonatomic, strong) UIView *view_login; //当前所有UI的parent view
@property (nonatomic, strong) BCTextField *textField_userName; //用户名框(输入手机号)
@property (nonatomic, strong) UIButton *button_next; //下一步按钮
@property (nonatomic, strong) UILabel *label_promtSystem; //输入提示
@property (nonatomic, strong) UILabel *label_promtPhoneNumber; //输入提示
@property (nonatomic, strong) UILabel *label_promtSecure; //安全提示

@property (nonatomic, strong) UIView *view_CellNumber; //手机号的父view,包括 label_promtPhoneNumber && textField_userName

@end

@implementation LoginViewController

#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    [self pageSettingsAndSubviewsCreation];
    [self setEdgesForExtendedLayout:UIRectEdgeNone];
}

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear: animated];
    [self.button_next setUserInteractionEnabled:YES];
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.navigationItem setTitle:@"注册"];
    [self.navigationItem setLeftBarButtonItem:nil];
    [self.view setBackgroundColor:BASECOLOR];
    
    // subviews
    [self.view addSubview:self.view_login];
    [self.view_login setFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(402.0/2))];
    
    [self.view_login addSubview:self.label_promtSystem];
    [self.view_login addSubview:self.label_promtSecure];
    [self.view_login addSubview:self.button_next];
    [self.view_login addSubview:self.view_CellNumber];
    // 手机号输入
    [self.view_CellNumber addSubview:self.textField_userName];
    [self.view_CellNumber addSubview:self.label_promtPhoneNumber];
    
    [self.label_promtSystem setFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(100.0/2))];
    
    [self.label_promtPhoneNumber setFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), 0, MULTIPLYWIDTH(100.0/2), MULTIPLYHEIGHT(100.0/2))];
    
    // 手机号输入
   
    [self.view_CellNumber addSubview:self.label_promtPhoneNumber];
     [self.view_CellNumber addSubview:self.textField_userName];
    [self.view_CellNumber setFrame:CGRectMake(0, CGRectGetMaxY(self.label_promtSystem.frame), SCREEN_WIDTH, MULTIPLYHEIGHT(100.0/2))];
    
//    [self.textField_userName setFrame:CGRectMake(CGRectGetMaxX(self.label_promtPhoneNumber.frame)+MULTIPLYWIDTH(20.0/2), 0, SCREEN_WIDTH - CGRectGetMaxX(self.label_promtPhoneNumber.frame) -MULTIPLYWIDTH(20.0/2) , MULTIPLYHEIGHT(100.0/2))];

    [self.button_next setFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(self.view_CellNumber.frame)+ MULTIPLYHEIGHT(62.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(90.0/2))];
    
    [self.label_promtSecure setFrame:CGRectMake(0, CGRectGetMaxY(self.button_next.frame) + MULTIPLYHEIGHT(20.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(30.0/2))];
}

#pragma mark - setter methods

- (UIView *)view_login {
    
    if (!_view_login) {
        
        _view_login = [[UIView alloc] init];
        [_view_login setBackgroundColor:BASECOLOR];
    }
    
    return _view_login;
}

- (UIView *)view_CellNumber {
    
    if (!_view_CellNumber) {
        
        _view_CellNumber = [[UIView alloc] init];
        [_view_CellNumber setBackgroundColor:[UIColor whiteColor]];
    }
    
    return _view_CellNumber;
}

- (UILabel *)label_promtSystem {
    
    if (!_label_promtSystem) {
        
        _label_promtSystem = [self createLabelWithTextColor:[UsefulUtil colorWithHexString:@"#434343"] andFont:[UIFont systemFontOfSize:15] andText:@"请输入手机号进行注册或登录"];
    }
    
    return _label_promtSystem;
}

- (UILabel *)label_promtPhoneNumber {
    
    if (!_label_promtPhoneNumber) {
        
        _label_promtPhoneNumber = [self createLabelWithTextColor:[UsefulUtil colorWithHexString:@"#434343"] andFont:[UIFont systemFontOfSize:15] andText:@"手机号:"];
        [_label_promtPhoneNumber setTextAlignment:NSTextAlignmentLeft];
    }
    
    return  _label_promtPhoneNumber;
}

- (UILabel *)label_promtSecure {
    
    if (!_label_promtSecure) {
        
        _label_promtSecure = [self createLabelWithTextColor:[UsefulUtil colorWithHexString:@"#5f5f61"] andFont:[UIFont systemFontOfSize:11] andText:@"牛板金不会在任何情况下泄漏您的手机号"];
    }
    
    return _label_promtSecure;
}

- (UILabel *) createLabelWithTextColor:(UIColor *) color andFont:(UIFont *) font andText:(NSString *) text{
    
    UILabel *label_tmp = [[UILabel alloc] init];
    [label_tmp setTextAlignment:NSTextAlignmentCenter];
    [label_tmp setTextColor:color];
    [label_tmp setFont:font];
    [label_tmp setText:text];
    [label_tmp setAdjustsFontSizeToFitWidth:YES];
    return  label_tmp;
}

- (UIButton *)button_next {
    
    if (!_button_next) {
        
        _button_next = [[UIButton alloc] init];
        
        [_button_next setBackgroundColor:[UsefulUtil colorWithHexString:@"#fb4747"]];
        [_button_next setTitle:@"下一步" forState:UIControlStateNormal];
        [_button_next.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_button_next addTarget:self action:@selector(buttonClickAtLoginPage:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _button_next;
}


- (BCTextField *)textField_userName {
    
    if (!_textField_userName) {
        
        _textField_userName = [[BCTextField alloc] initWithFrame:CGRectMake(MULTIPLYWIDTH(130.0/2)+MULTIPLYWIDTH(20.0/2), 0, SCREEN_WIDTH - MULTIPLYWIDTH(130.0/2) -MULTIPLYWIDTH(20.0/2) , MULTIPLYHEIGHT(100.0/2))];
        
        [_textField_userName setPlaceholder:@"请输入手机号即用户名"];
        [_textField_userName setKeyboardType:UIKeyboardTypeNumberPad];
        [_textField_userName setClearButtonMode:UITextFieldViewModeWhileEditing];
        
        [_textField_userName setAdjustsFontSizeToFitWidth:YES];
        [_textField_userName setRegx:@"^[0-9]{1,11}$"];
        [_textField_userName setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
      
    }
    
    return  _textField_userName;
}

#pragma mark - keyboard eventsHanding

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self setEditing:NO];
}

// here no need to implement such gesture method
- (void) swiperGestureHandle:(UISwipeGestureRecognizer *) swipe {
    
}

#pragma mark - button eventsHanding

- (void) buttonClickAtLoginPage:(UIButton *) button {
    
    [self.view endEditing:YES]; //收起键盘
    
    if ([self.textField_userName.text isEqualToString:@""]) {
        
        [UsefulUtil showAlertView:@"手机号不能为空"];
        return;
    }
    
    if ( ![UsefulUtil isMobileNumber:self.textField_userName.text]) {
        
        [UsefulUtil showAlertView:@"请输入正确的手机号"];
    } else {
        
        [[NSUserDefaults standardUserDefaults] setObject:self.textField_userName.text forKey:@"mobile"]; //这儿保存一个电话号码为了以后做准备
        [[NSUserDefaults standardUserDefaults] synchronize];
        // 输入正确，验证新老用户的接口访问
        [self.button_next setUserInteractionEnabled:NO];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //进度条
        
        NSDictionary *dic_params = @{@"mobile":self.textField_userName.text};
        
        [[NetworkUtil sharedNetworkUtil] zzjrUserTypeCheckingByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (!error) {  //没有网络错误
                
                // 开始解析数据
                NSDictionary *dic = parsedData;
                
                if([dic[@"status"] intValue] == 0) {
                    
                    NSString *result = [NSString stringWithFormat:@"%@",dic[@"result"][@"userType"]];
                   [result isEqualToString:@"0"] ? [self existingUserInterface] : [self newUserInterface];
                } else {// 不是网络出错，是密码错 or 其它错误
                    
                    [UsefulUtil showAlertView:dic[@"msg"]];
                    [self.button_next setUserInteractionEnabled:YES];
                }
            }else {
                
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [UsefulUtil showAlertView:error.description];
                [self.button_next setUserInteractionEnabled:YES];
            }
        }];
    }
}

- (void) existingUserInterface { //老用户

    dispatch_async(dispatch_get_main_queue(), ^(void){
        
        [CLLockVC showVerifyLockVCInVC:self forgetPwdBlock:^{
            
            //忘记密码, 跳到我们的UI进行修改
            
            RegisterViewController *forgetVC = [[RegisterViewController alloc] init];
            
            [forgetVC setStr_type:@"retrievePassword"];
            [forgetVC setStr_cellNumber:self.textField_userName.text];
            
            [self.navigationController pushViewController:forgetVC animated:YES];
            
        } successBlock:^(CLLockVC *lockVC, NSString *pwd) {
            
            [MBProgressHUD showHUDAddedTo:lockVC.view animated:YES]; //进度条
            
            NSDictionary *dic_paras = @{@"mobile":self.textField_userName.text,@"gesturePassword":pwd,@"udidStr":[UsefulUtil getUDIDOfCurrentDevice]};
            
            [[NetworkUtil sharedNetworkUtil] zzjrUserLoginByParmeteres:dic_paras transferResultUsingBlock:^(id parsedData, NSError *error) {
                
                [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                if (!error) {  //没有网络错误
                    
                    // 开始解析数据
                    NSDictionary *dic = parsedData;
                    
                    if([dic[@"status"] intValue] == 0) {
                        
                        // 保存用户重要信息
                            
                        User *user = [[User alloc] initWithAttributes:dic[@"result"]];
                        [[UserManager sharedUserManager] setUser:user];
                        [[UserManager sharedUserManager] saveCurrentUser:user];
                        
                        CURRENT_WINDOW.rootViewController = [CustomTabBarViewController new];
                        [lockVC dismiss:0];
                    } else {// 不是网络出错，是密码错 or 其它错误
                        [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                        [lockVC.view setUserInteractionEnabled:YES];
                        
                        [UsefulUtil showAlertView:dic[@"msg"]];
                         [self existingUserInterface]; //递归调用直到正确
                    }
                }else {
                    
                    [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                    [UsefulUtil showAlertView:error.description];
                }
            }];
        }];
    });
    
}

- (void) newUserInterface { //新用户
    
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [registerVC setStr_cellNumber:self.textField_userName.text];
    [registerVC setStr_type:@"register"];
    
    [self.navigationController pushViewController:registerVC animated:YES];
}

#pragma mark - memory warning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
